package cn.lingyangwl.agile.infra.gen.manager;

import cn.hutool.core.collection.CollUtil;
import cn.lingyangwl.agile.infra.gen.mapper.*;
import cn.lingyangwl.agile.infra.gen.model.entity.*;
import cn.lingyangwl.agile.infra.gen.model.rqrs.*;
import cn.lingyangwl.framework.mybatis.plus.utils.*;
import cn.lingyangwl.framework.tool.core.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Repository
public class GenTableManager extends ServiceImpl<GenTableMapper, GenTable> implements IService<GenTable> {
    @Resource
    private GenTableMapper genTableMapper;

    public void saveImportTable(GenTable req) {
        String tableName = req.getTableName();
        LambdaQueryWrapper<GenTable> wrapper = GenTable.lqw()
                .eq(GenTable::getTableName, tableName).eq(GenTable::getDatasourceId, req.getDatasourceId());
        GenTable genTable = genTableMapper.selectOne(wrapper);
        if (Objects.nonNull(genTable)) {
            req.setId(genTable.getId());
            req.setDescription(null);
            genTableMapper.updateById(req);
        } else {
            genTableMapper.insert(req);
        }
    }

    public IPage<GenTable> pageGenTable(GenTablePageReq req) {
        LambdaQueryWrapper<GenTable> wrapper = GenTable.lqw()
                .like(StringUtils.isNotEmpty(req.getTableName()), GenTable::getTableName, req.getTableName())
                .like(StringUtils.isNotEmpty(req.getTableComment()), GenTable::getTableComment, req.getTableComment())
                .eq(Objects.nonNull(req.getDatasourceId()), GenTable::getDatasourceId, req.getDatasourceId())
                .orderByDesc(GenTable::getUpdatedAt);
        return this.page(PageUtil.to(req), wrapper);
    }

    public List<GenTable> listByDatasourceId(Long datasourceId) {
        LambdaQueryWrapper<GenTable> wrapper = GenTable.lqw().eq(GenTable::getDatasourceId, datasourceId);
        return this.list(wrapper);
    }

    public List<GenTable> listByTableNames(Long datasourceId, List<String> tableNames) {
        LambdaQueryWrapper<GenTable> lqw = GenTable.lqw()
            .in(CollUtil.isNotEmpty(tableNames), GenTable::getTableName, tableNames)
            .eq(GenTable::getDatasourceId, datasourceId)
            .orderByDesc(GenTable::getUpdatedAt);
        return list(lqw);
    }
}
